package springboot.rabbitmq.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springboot.rabbitmq.config.DelayedQueueConfig;

import java.util.Date;

@Slf4j
@RestController
@RequestMapping(value = "/ttl")
public class SendMessageController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    // 发送消息
    @GetMapping(value = "/sendMsg/{message}")
    public void sendMessage(@PathVariable(value = "message") String message) {
        log.info("当前时间:{},发送一条消息给两个TTL队列:{}", new Date().toLocaleString(), message);
        rabbitTemplate.convertAndSend("X", "XA", "消息来自ttl为10s的队列:" + message);
        rabbitTemplate.convertAndSend("X", "XB", "消息来自ttl为40s的队列:" + message);
    }

    // 发送一个带过期时间的消息
    @GetMapping("/sendExpirationMessage/{message}/{timeToLive}")
    public void sendMessage(@PathVariable String message, @PathVariable String timeToLive) {
        int temp = Integer.parseInt(timeToLive);
        String ttl = String.valueOf(temp * 1000);
        log.info("当前时间:{},发送一条过期时间为:{}ms的消息{}给队列QC", new Date().toLocaleString(), ttl, message);
        rabbitTemplate.convertAndSend("X", "XC", message, msg -> {
            msg.getMessageProperties().setExpiration(ttl);
            return msg;
        });
    }

    // 发送基于插件的延迟消息
    @GetMapping(value = "/sendDelayedMessage/{message}/{delayTime}")
    public void sendMessage(@PathVariable String message, @PathVariable Integer delayTime) {
        log.info("当前时间:{},发送一条过期时间为:{}ms的消息{}给队列QC", new Date().toLocaleString(), delayTime, message);
        rabbitTemplate.convertAndSend(DelayedQueueConfig.DELAYED_EXCHANGE_NAME,
                DelayedQueueConfig.DELAYED_ROUTING_KEY_NAME, message, msg -> {
                    msg.getMessageProperties().setDelay(delayTime);
                    return msg;
                });
    }
}
